#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" http://blog.notdot.net/2010/04/Implementing-a-dropbox-service-with-the-Blobstore-API-part-2 , 
nik3.py
""" 

import cgi
import datetime
import urllib
import webapp2

import jinja2
import os

from google.appengine.api import images
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class FileInfo(db.Model):
  blob = blobstore.BlobReferenceProperty(required=True)
  uploaded_by = db.UserProperty(required=True)
  uploaded_at = db.DateTimeProperty(required=True, auto_now_add=True)


class BaseHandler(webapp2.RequestHandler):
  def render_template(self, file, template_args):
    path = os.path.join(os.path.dirname(__file__), "templates", file)
    self.response.out.write(template.render(path, template_args)) 


class FileUploadFormHandler(BaseHandler):
  @util.login_required
  def get(self):
    template_values = {
            'logout_url': users.create_logout_url('/'),
    }
    template = jinja_environment.get_template('upload3.html')
    self.response.out.write(template.render(template_values))


class FileUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    blob_info = self.get_uploads()[0]
    if not users.get_current_user():
      blob_info.delete()
      self.redirect(users.create_login_url("/"))
      return
    file_info = FileInfo(blob=blob_info.key(),
                         uploaded_by=users.get_current_user())
    db.put(file_info)
    """self.redirect("/file/%d" % (file_info.key().id(),))"""
    self.redirect("/file/%d/success" % (file_info.key().id(),))


class AjaxSuccessHandler(BaseHandler):
  def get(self, file_id):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('%s/file/%s' % (self.request.host_url, file_id))


class FileInfoHandler(BaseHandler):
  def get(self, file_id):
    file_info = FileInfo.get_by_id(long(file_id))
    if not file_info:
      self.error(404)
      return
    template_values = {
            'file_info': file_info,
            'logout_url': users.create_logout_url('/'),
    }
    template = jinja_environment.get_template('info.html')
    self.response.out.write(template.render(template_values))


class FileDownloadHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, file_id):
    file_info = FileInfo.get_by_id(long(file_id))
    if not file_info or not file_info.blob:
      self.error(404)
      return
    self.send_blob(file_info.blob, save_as=True)


class GenerateUploadUrlHandler(BaseHandler):
  @util.login_required
  def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write(blobstore.create_upload_url('/upload'))	


app = webapp2.WSGIApplication([
     ('/', FileUploadFormHandler),
     ('/upload', FileUploadHandler),
     ('/generate_upload_url', GenerateUploadUrlHandler),
     ('/file/([0-9]+)', FileInfoHandler),
     ('/file/([0-9]+)/download', FileDownloadHandler),
     ('/file/([0-9]+)/success', AjaxSuccessHandler)],
    debug=True) 
